package top.lidee.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import com.thoughtworks.xstream.core.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.lidee.framework.annoation.AutAccess;
import top.lidee.framework.constant.AppletRedisKeysConstant;
import top.lidee.framework.constant.GlobalHeadConstant;
import top.lidee.framework.enums.CommonExceptionEnum;
import top.lidee.repository.model.twice.local.LoginUserLoc;
import top.lidee.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 小程序路径拦截器
 * @date 2024/8/27 09:25
 */
@Component
@Slf4j
public class AppletInterceptor implements HandlerInterceptor {


    public static final ThreadLocal<LoginUserLoc> APPLETTHREADLOCAL = new ThreadLocal<>();

//    public static final ThreadLocal<ManagerLoginVo> MANAGERTHREADLOCAL = new ThreadLocal<>();

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //加了AutAccess注解直接放行
        if (handler instanceof HandlerMethod) {
            AutAccess handlerMethod = ((HandlerMethod) handler).getMethodAnnotation(AutAccess.class);
            if (handlerMethod != null) {
                return true;
            }
        }


        //获取token
        String token = request.getHeader(GlobalHeadConstant.AUTHORIZATION);

        //401
        if (StrUtil.isBlank(token)) {
            throw new BeanCreationException(CommonExceptionEnum.NOAUTH.getMsg());
        }

        //判断JWT准确性/是否过期
        if (!JwtUtil.isSigned(token) && JwtUtil.isExpired(token)) {
            throw new BeanCreationException(CommonExceptionEnum.TOKEN_ERROR.getMsg());
        }

        //校验签名
        if (!JwtUtil.verify(token)) {
            throw new BeanCreationException(CommonExceptionEnum.TOKEN_ERROR.getMsg());
        }

        //获取用户信息
        String info = JwtUtil.getPayloadByBase64(token);


        LoginUserLoc loginUserLoc = JSON.parseObject(Optional.ofNullable(info).orElse(""), LoginUserLoc.class);
        if (!Objects.isNull(loginUserLoc)) {
            //校验小程序用户信息
            Object res = redisTemplate.opsForValue().get(AppletRedisKeysConstant.APPLET_LOGIN + loginUserLoc.getUserId());
            if (Objects.isNull(res)) {
                throw new BeanCreationException(CommonExceptionEnum.DATE_CHANGE_ERROR.getMsg());
            }
            //登录成功 保存当前线程用户信息
            APPLETTHREADLOCAL.set(loginUserLoc);
            log.info("{} 线程用户信息：{}", Thread.currentThread().getName(), loginUserLoc);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        APPLETTHREADLOCAL.remove();
//        MANAGERTHREADLOCAL.remove();
//        log.debug("本地线程域存储情况：applet:{},manager:{}",
//                Optional.of(APPLETTHREADLOCAL).orElse(null)
//                , Optional.of(MANAGERTHREADLOCAL).orElse(null));
    }

}



